package com.tone.ji_volunteer.service.impl;

import com.tone.ji_volunteer.mapper.UserMapper;
import com.tone.ji_volunteer.pojo.Code;
import com.tone.ji_volunteer.pojo.User;
import com.tone.ji_volunteer.service.LoginService;
import com.tone.ji_volunteer.util.JWT;
import com.tone.ji_volunteer.util.WxLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tone(ang)
 * version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private WxLogin wxLogin;
    @Autowired
    private JWT jwt;
    @Autowired
    private UserMapper userMapper;
    @Override
    public String login(Map<String, Object> codeData) {
        String nickName = (String) codeData.get("nickName");
        Integer gender = (Integer) codeData.get("gender");
        String code = (String) codeData.get("code");
        String perSig = (String) codeData.get("perSig");



        Map<String, Object> session = wxLogin.getSession(code);
        //在数据库中搜素用户，如果存在，将信息取出
        // 从 session 中获取 openid 和 session_key
        String openid = (String) session.get("openid");
        //数据库没有添加，有无操作
        User user = userMapper.select(openid);

        User user1 = new User(null, nickName, gender, openid, perSig);
        if(user == null ){
            //添加
            userMapper.addUser(user1);
        } else if (user.getGender() != gender || user.getNickname() != nickName || user.getPerSig() != perSig) {
            //修改
            userMapper.update(user1);
        }
        //生成JWT令牌
        String s = jwt.generateJwt(session);
        return s;
    }
}
